package com.itheima.order.service.impl;

import com.itheima.feign.goods.GoodsFeign;
import com.itheima.feign.user.UserFeign;
import com.itheima.goods.pojo.Address;
import com.itheima.goods.pojo.Order;
import com.itheima.order.mapper.OrderMapper;
import com.itheima.order.service.OrderService;
import entity.Result;
import entity.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    GoodsFeign goodsFeign;
    @Autowired
    UserFeign userFeign;
    @Autowired
    OrderMapper orderMapper;
    @Override
    public Result findSubmitInfoById(Long id) {
// A. 根据当前登录用户名，查询该用户对应的收获地址列表,假的登录,所以写死登录name
        List<Address> addressList = userFeign.findByUserName("itcast123");
//B. 根据要购买商品ID，查询该商品信息
        Result goodsResult = goodsFeign.findById(id);
//C. 根据选择的收货地址信息，和商品信息 创建订单数据
        Map map = new HashMap();
        map.put("addressList", addressList);
        map.put("goods", goodsResult.getData());
        return new Result(true, StatusCode.OK, "查询成功", map);
    }


    @Override
    public Result submitOrder(Order order) {
        //没有传订单参数或没有订单号
        if (order == null || order.getId() == null) {
            return new Result(false, StatusCode.ERROR, "订单获取失败");
        }
        //订单已经存在
        if (orderMapper.selectById(order.getId())!=null){
            return new Result(false, StatusCode.ERROR, "此订单已存在,不可重复插入订单");
        }
        //新订单存在并且不重复,则删减对应id的商品库存
        Result buy = goodsFeign.buy(order.getGoodId(), order.getTotalNum());
        //库存删减失败
        if (!buy.isFlag()){
            return new Result(false, StatusCode.ERROR, buy.getMessage());
        }
        //库存删减成功
        order.setCreateTime(new Date());
        order.setUpdateTime(new Date());
        //订单状态1
        order.setOrderStatus("1");
        //插入订单数据
        orderMapper.insert(order);
        return new Result(true,StatusCode.OK,"订单添加成功",order.getId());

    }
}
